package user

import (
	"context"
	"github.com/mojocn/base64Captcha"
	"go-zero-project/services/user/api/constans"
	"image/color"
	"time"

	"go-zero-project/services/user/api/internal/svc"
	"go-zero-project/services/user/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CaptchaLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCaptchaLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CaptchaLogic {
	return &CaptchaLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func newDriver() *base64Captcha.DriverString {
	// 配置验证码的参数
	driverString := base64Captcha.DriverString{
		Height:          40,
		Width:           100,
		NoiseCount:      0,
		ShowLineOptions: 2 | 4,
		Length:          6,
		Source:          base64Captcha.TxtAlphabet + base64Captcha.TxtNumbers,
		BgColor:         &color.RGBA{R: 3, G: 102, B: 214, A: 125},
		Fonts:           []string{"wqy-microhei.ttc"},
	}
	// ConvertFonts 按名称加载字体
	driver := driverString.ConvertFonts()
	return driver
}

func (l *CaptchaLogic) Captcha() (resp *types.GetCaptchaResp, err error) {
	// 设置验证码大小
	driver := newDriver()
	// 构建图片验证码
	captcha := base64Captcha.NewCaptcha(driver, base64Captcha.DefaultMemStore)
	// 生成base64 图片
	generate, b64s, err := captcha.Generate()
	if err != nil {
		logx.Error("generate auth code image failed %s", err)
		return nil, err
	}
	redisKey := constans.CaptchaRedisKeyPrefix + generate
	// 设置进入缓存 60秒过期
	verifyCode := captcha.Store.Get(generate, true)
	statusCmd := l.svcCtx.RedisClient.Set(l.ctx, redisKey, verifyCode, 120*time.Second)
	if statusCmd.Err() != nil {
		logx.Error("setting auth code in  redis failed %s", err)
		return nil, statusCmd.Err()
	}
	return &types.GetCaptchaResp{CaptchaId: generate, PicPath: b64s}, nil
}
